package com.example.kotlinlearningproject

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.media.MediaPlayer
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import com.example.kotlinlearningproject.audioplayer.SoundPoolPlayer
import com.example.kotlinlearningproject.databinding.ActivityMainBinding
import com.example.kotlinlearningproject.helper.BitmapBinder
import com.example.kotlinlearningproject.nativelib.NativeTest
import com.example.kotlinlearningproject.network.DownloadHandler
import com.example.kotlinlearningproject.network.NetworkHelper
import com.example.kotlinlearningproject.ui.activity.CameraActivity
import com.example.kotlinlearningproject.ui.activity.SecondActivity
import com.example.kotlinlearningproject.utils.AudioUtil
import com.example.kotlinlearningproject.utils.Const
import com.example.kotlinlearningproject.utils.DeviceIdUtil
import com.example.kotlinlearningproject.utils.FileUtil
import com.example.kotlinlearningproject.utils.ImageUtil
import com.github.promeg.pinyinhelper.Pinyin
import com.github.promeg.tinypinyin.lexicons.android.cncity.CnCityDict
import kotlin.concurrent.thread

private const val TAG = "MainActivity"

class MainActivity : ComponentActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var soundPoolPlayer: SoundPoolPlayer
    private lateinit var mediaPlayer: MediaPlayer

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initButtons()
        onBackPressedDispatcher.addCallback(this, onBackPress)
    }

    @SuppressLint("HardwareIds", "SetTextI18n")
    private fun initButtons() {
        // 1.SoundPool播放mp3
        soundPoolPlayer = SoundPoolPlayer()
        soundPoolPlayer.preload(assets)
        binding.btnPlay.setOnClickListener { soundPoolPlayer.playIKnowMp3() }

        // 2.测试tinypinyin
        Pinyin.init(Pinyin.newConfig().with(CnCityDict.getInstance(this)))
        binding.btnTinyPinyin.setOnClickListener {
            val pinyin = Pinyin.toPinyin("这里是中国", "")
            Log.d(TAG, "拼音转为: ${pinyin} **********")
        }

        // 3.使用retrofit调用翻译接口
        binding.btnTranslate.setOnClickListener { NetworkHelper().translate() }

        // 4.MediaPlayer播放线上音频
        mediaPlayer = MediaPlayer()
        binding.btnMediaPlay.setOnClickListener {
            if (mediaPlayer.isPlaying) {
                mediaPlayer.stop()
            } else {
                mediaPlayer.reset() //多次点击需要重置
                mediaPlayer.setDataSource(Const.AUDIO_URL)
                // 同步准备并播放
                mediaPlayer.prepare()
                Log.d(TAG, "prepare完成**********")
                mediaPlayer.start()
                Log.d(TAG, "播放**********")
            }
        }
        // 5.MediaPlayer异步播放线上音频
        binding.btnMediaPlay2.setOnClickListener {
            if (mediaPlayer.isPlaying) {
                mediaPlayer.stop()
            } else {
                mediaPlayer.reset() //多次点击需要重置
                mediaPlayer.setDataSource(Const.AUDIO_URL)
                // 同步准备并播放
                mediaPlayer.prepareAsync()
                mediaPlayer.setOnPreparedListener {
                    mediaPlayer.start()
                }
                mediaPlayer.setOnCompletionListener {
                    Log.d(TAG, "播放完成**********")
                }
            }
        }
        // 6.获取设备唯一标识
        val androidDeviceId =
            Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
        binding.tvShowMsg.text = ("DEVICEID: " + DeviceIdUtil.getMEID() + "\n"
                + "Mac: " + DeviceIdUtil.getMacAddress(this) + "\n"
                + "Android Id: " + androidDeviceId + "\n"
                + "UniqueID: " + DeviceIdUtil.getUniqueID(this));
        // 7.下载一个mp3文件，存放在
        binding.btnDownload.setOnClickListener { requestPermission() }
        // 8. 同步下载wav文件
        binding.btnDownloadSync.setOnClickListener {
            thread {
                DownloadHandler(this).downloadAudioSync(Const.AUDIO_URL)
            }
        }
        // 9.删除目录下的wav文件，采用遍历文件比对后缀的方式删除
        binding.btnDeleteWav.setOnClickListener { FileUtil.deleteWavFilesTest(this) }
        // 10.音量控制
        val audioUtil = AudioUtil(this)
        binding.btnMute.setOnClickListener { audioUtil.mute() }
        binding.btnUnmute.setOnClickListener { audioUtil.setMaxVolume() }
        binding.btnIncrease.setOnClickListener { audioUtil.increaseVolume() }
        binding.btnDecrease.setOnClickListener { audioUtil.decreaseVolume() }
        // 11.imageview显示asserts里面的图片
        val image = ImageUtil.loadImageFromAssets("test.png",assets);
        binding.imgTest.setImageBitmap(image)
        // 12.两个activity传输大bitmap图片
        binding.btnGotoSecond.setOnClickListener {
            if (image != null) {
                transferBitmap(image)
            }
        }
        // 切换到扬声器播放
        binding.btnSpeaker.setOnClickListener { audioUtil.changeToSpeaker() }
        binding.btnCamera.setOnClickListener { startCameraActivity() }
        binding.btnNdk.setOnClickListener { testNdk() }
    }

    private fun testNdk() {
        val test = NativeTest()
        val result = test.add(23,90)
        Toast.makeText(this, "调用NDK计算：${result}", Toast.LENGTH_SHORT).show()
    }

    private fun startCameraActivity() {
        startActivity(Intent(this, CameraActivity::class.java))
    }

    private fun transferBitmap(image: Bitmap) {
        val intent = Intent(this, SecondActivity::class.java)
//        intent.putExtra(Const.INTENT_IMAGE, image)
        val bundle = Bundle()
        val bitmapBinder = BitmapBinder(image)
        bundle.putBinder(Const.INTENT_IMAGE,bitmapBinder)
        intent.putExtras(bundle)
        startActivity(intent)
    }

    private var permissionLauncher: ActivityResultLauncher<Array<String>> = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { result ->
        var isDenyAll = true
        result.entries.forEach {
            isDenyAll = isDenyAll and it.value
        }

        if (isDenyAll) {
            // 权限没有得到
            Toast.makeText(this, "没有授权！", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "已授权！", Toast.LENGTH_SHORT).show()
            // 下载音频
            DownloadHandler(this).downloadAudio(Const.AUDIO_URL)
        }
    }

    private fun requestPermission() {
        if (ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)
            == PackageManager.PERMISSION_GRANTED
            && ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE)
            == PackageManager.PERMISSION_GRANTED
        ) {
            Toast.makeText(this, "已授权！", Toast.LENGTH_SHORT).show()
            // 下载音频
            DownloadHandler(this).downloadAudio(Const.AUDIO_URL)
        } else {
            permissionLauncher.launch(
                arrayOf(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                )
            )
        }
    }

    private val onBackPress = object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            Log.d(TAG, "handleOnBackPressed,退出应用**********")
            //退出应用
            showDialog()
        }
    }

    private fun showDialog() {
        val builder = AlertDialog.Builder(this)
        builder.setTitle("尊敬的用户")
        builder.setMessage("你真的要退出吗？")
        builder.setPositiveButton("残忍退出") { _, _ ->
            finish()
        }
        builder.setNegativeButton("我再想想") {dialog, which ->
            // do nothing
        }
        val alert = builder.create()
        alert.show()
    }

    override fun onDestroy() {
        super.onDestroy()
        mediaPlayer.stop()
        mediaPlayer.release()
    }
}
